package com.golookon.managed;

import java.io.IOException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.primefaces.event.SelectEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.golookon.dao.MenuDao;
import com.golookon.entity.Menu;
import com.golookon.entity.MenuItem;

@Component("menuManager")
@Scope("session")
public class MenuManager {

	@Inject
	MenuDao md;

	private String url;
	private Menu menu;
	private List<Menu> allMenus;
	private List<Menu> resultMenus;
	private Menu selectedMenu;
	private String searchTerm;

	@PostConstruct
	public void init() {
		loadMenus();
	}

	public void loadMenus() {
		allMenus = md.getAllMenus();
	}

	public String persistMenu() {
		try {
			// String url =
			// "http://www.grubhub.com/doSearch.action?rawSearchAddress=George+Mason+University+-+Fairfax%2C+Fairfax%2C+VA&restaurantType=BOTH&cityId=4&custId=262565&lat=38.828215&lng=-77.309787&queryAddress=George+Mason+University+-+Fairfax&queryCity=Fairfax&queryState=VA&searchAddressStr=George+Mason+University+-+Fairfax%2C+Fairfax%2C+VA&searchSortMode=DEFAULT_NEW&campusId=191&restaurantType=BOTH&stateDataString=custId%3D82212%2CqueryCity%3DFairfax%2CqueryState%3DVA%2Cpage%3Ddetails%2Csecure%3Dfalse%2CcityId%3D4%2Clat%3D38.828215%2Clng%3D-77.309787%2CrestaurantType%3DBOTH%2CsearchAddress%3DGeorge+Mason+University+-+Fairfax%2C+Fairfax%2C+VA%2Curlinfoid%3D1%2CqueryAddress%3DGeorge+Mason+University+-+Fairfax%2CcampusId%3D191%2Csearchable%3Dtrue%2Cdeliverable%3Dfalse%2Cverified%3Dfalse%2CpoiSearchTerm%3Dnull&selectCustomer=Y";
			Document doc = Jsoup.connect(url).get();
			String title = doc.select("h1.site_h1").first().text();
			String contact = doc.select("div.fine_print").first().text();
			// String title = "Best Deli";
			menu = new Menu();
			menu.setName(title);
			menu.setContact(contact);
			md.persist(menu);

			Elements categories = doc.select("h5.site_h2");
			Elements menuItems = doc.select("ul.menuItems");

			for (int i = 0; i < categories.size(); i++) {
				String currentCategory = categories.get(i).text();
				Element currentMenuItems = menuItems.get(i);

				Elements items = currentMenuItems.children();
				for (Element item : items) {
					String itemName = item.getElementsByClass("item_name")
							.text();
					String itemPrice = item.getElementsByClass("item_price")
							.text();
					MenuItem mi = new MenuItem();
					mi.setCategory(currentCategory);
					mi.setName(itemName);
					mi.setPrice(itemPrice);
					mi.setMenu(menu);
					md.persist(mi);

				}
			}
			loadMenus();
			return "success";

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "fail";
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Menu getMenu() {
		return menu;
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}

	public List<Menu> getAllMenus() {
		return allMenus;
	}

	public void setAllMenus(List<Menu> allMenus) {
		this.allMenus = allMenus;
	}

	public Menu getSelectedMenu() {
		return selectedMenu;
	}

	public void setSelectedMenu(Menu selectedMenu) {
		this.selectedMenu = selectedMenu;
	}

	public List<Menu> getResultMenus() {
		return resultMenus;
	}

	public void setResultMenus(List<Menu> resultMenus) {
		this.resultMenus = resultMenus;
	}

	public String getSearchTerm() {
		return searchTerm;
	}

	public void setSearchTerm(String searchTerm) {
		this.searchTerm = searchTerm;
	}

	public void onRowSelect(SelectEvent event) {
		selectedMenu = (Menu) event.getObject();
		// System.out.println("Row Selected.");
		try {
			FacesContext.getCurrentInstance().getExternalContext()
					.redirect("menuDetail.xhtml");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String search() {
		String wrappedSearchTerm;
		if (!searchTerm.contains(" "))
			wrappedSearchTerm = "%" + searchTerm + "%";
		else {
			String[] keywords = searchTerm.split(" ");
			StringBuffer temp =  new StringBuffer();
			temp.append("%");
			for(String keyword:keywords){
				temp.append(keyword+"%");
			}
			wrappedSearchTerm = temp.toString();
		}
		resultMenus = md.searchMenus(wrappedSearchTerm);
		
		return "searchResult?faces-redirect=true";
	}

}
